Dynamically Update Attribute Values


To change the attributes of multiple elements based on user input or other dynamic conditions. Use setAttribute to update attributes for multiple elements.

Let say you want to show image by selecting from dropdown.

<!-- Dropdown -->
<select id="imageSelector">
     <option value="image1.jpg" data-alt="Image 1 Description">Image 1</option>
     <option value="image2.jpg" data-alt="Image 2 Description">Image 2</option>
     <option value="image3.jpg" data-alt="Image 3 Description">Image 3</option>
</select>

<!-- Show image here -->
<div id="gallery">
   <img id="mainImage" src="default.jpg" alt="Default Image">
</div>

Javascript:

<script>
    document.getElementById('imageSelector').addEventListener('change', function() {

        // get selected item's url and alt 
        const selectedOption = this.options[this.selectedIndex];
        const imageUrl = selectedOption.value;
        const imageAlt = selectedOption.getAttribute('data-alt');

        const mainImage = document.getElementById('mainImage');
        mainImage.setAttribute('src', imageUrl); // set url of image
        mainImage.setAttribute('alt', imageAlt); // set alt attribute of image
    });
</script>

You Might Also Like

Apply Styles to Multiple Elements

Apply a style to multiple elements at once by adding a class. Here highlighting selected list items...

Remove Multiple DOM Elements

Use a loop to detach elements and then remove them all at once. ``` const elementsToRemove = docum...